<template>
  <a-card :bordered="false">
    <h3>中奖名单</h3>
     <a-form-model
      :wrapperCol="{ span: 24 }"
    >
      <a-form-model-item label="话题名称">
        <template v-if="topicName">#{{topicName}}</template>
      </a-form-model-item>
      <a-form-model-item label="获奖方式">
        <template v-if="rewardWhy == 0">按点赞数排名获奖</template>
      </a-form-model-item>
      <a-form-model-item label="中奖名单">
        <div style="display: flex;justify-content: space-between;">
          <div style="font-size: 12px;color: #999;">中奖结果将在话题活动结束后15分钟内完成统计内容赞数相同将根据内容的浏览量从大到小排名；浏览量也相同，则按照发布时间从早到晚排名</div>
          <a-button type="primary" icon="cloud-download" @click="handleWinningExport">导出中奖名单</a-button>
        </div>
        <a-table :scroll="{ x: true }" :pagination="false" :columns="columns" :data-source="winningList" :rowKey="(record, index) => index">
          <span slot="serialNumber" slot-scope="text, record, index">
           {{record.serialNumber}}等奖
          </span>
          <span slot="userInfo" slot-scope="text, record, index">
            {{record.userNickname}}/{{record.phone}}（社区ID：{{record.userId}}）
          </span>
          <span slot="customAddress">收货地址 
            <a-tooltip>
              <template slot="title">
                收货地址会默认取出用户微商城的默认收货地址，实物发货前，请和顾客二次确认发货地址，确保用户地址准确
              </template>
              <a-icon type="question-circle" />
            </a-tooltip>
          </span>
          <span slot="content" slot-scope="text, record, index">
            <span class="title">{{record.contentTitle}}</span>
            <span class="content">{{record.bodyContent}}</span>
            <div class="content-btn" @click="handleDetails(record.contentId)">
              <span>内容ID：{{record.contentId}}</span>
              <span>查看></span>        
            </div>
          </span>
          <span slot="rewardType" slot-scope="text, record, index">
            <span v-if="record.rewardType == 0">优惠券</span>
            <span v-if="record.rewardType == 1">实物</span>
          </span>
          <span slot="img" slot-scope="text, record, index">
            <img class="img" :src="record.rewardImage" alt="">
          </span>
          <span slot="address" slot-scope="text, record, index">
            <template v-if="record.rewardType == 1">
              {{record.shippingName || ''}}<template v-if="record.shippingName">，</template>
              {{record.province || ''}}<template v-if="record.province">，</template>
              {{record.city || ''}}<template v-if="record.city">，</template>
              {{record.area || ''}}<template v-if="record.area">，</template>
              {{record.shippingAddress}}
              <a-icon type="form" style="color: rgb(87, 87, 255);cursor: pointer;" @click="handleShowAddressModal(record)" />
            </template>
            <template v-if="record.rewardType == 0">/</template>
          </span>
          <span slot="status" slot-scope="text, record, index">
            <template v-if="record.status == 0">
              <div style="color: #09bb07;">已发放奖励</div>
              <template v-if="record.orderNo">（物流单号：{{record.orderNo}}）</template>
            </template>
            <template v-if="record.status == 1">未发放奖励</template>
          </span>
          <span slot="action" slot-scope="text, record, index">
            <a-popconfirm
              v-if="record.status == 1 && record.rewardType == 0"
              title="确定给该用户发放优惠券奖励吗？"
              ok-text="确定"
              @confirm="handleIssueCoupons(record)"
            >
              <a>发放奖励</a>
            </a-popconfirm>
            <a v-else-if="record.status == 1 && record.rewardType == 1" @click="handleShowExpressModal(record)">发放奖励</a>
            <a v-else :disabled="true">--</a>
          </span>      
        </a-table>
      </a-form-model-item>
      <a-form-model-item :wrapperCol="{ span: 24 }">
        <a-button @click="$router.go(-1)">返回话题列表</a-button>
      </a-form-model-item>
    </a-form-model>
    <!-- 发放奖励 -->
    <a-modal :visible="expressVisible" width="500px" @ok="handleIssueGoods"
             @cancel="expressVisible = false">
      <a-form-model
      ref="expressRulesForm"
      :model="expressForm"
      :rules="expressRules"
    >
        <div style="text-align:center;margin-top: 20px;">该用户为实物奖励，请联系顾客获取收货地址，安排奖品寄出后，再填写快递单号</div>
        <a-form-model-item prop="express">
          <a-input v-model="expressForm.express" placeholder="请填写奖品寄出的物流单号" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>

    <!-- 修改收货信息 -->
    <a-modal title="修改收货信息" :visible="addressVisible" width="600px" @ok="handleSubmit"
             @cancel="addressVisible = false">
      <a-form-model
      ref="addressRulesForm"
      :model="addressForm"
      :rules="addressRules"
      :labelCol="{ span: 4 }"
      :wrapperCol="{ span: 20 }"
    >
        <a-form-model-item label="收货人姓名" prop="shippingName">
          <a-input v-model="addressForm.shippingName" placeholder="" />
        </a-form-model-item>
        <a-form-model-item label="收货人电话" prop="phone">
          <a-input v-model="addressForm.phone" placeholder="" />
        </a-form-model-item>
        <a-form-model-item label="收货地址" required>
          <a-row :gutter="5">
            <a-col :span="8">
              <a-form-model-item label="" style="width: 100%;" prop="provinceId">
                <a-select v-model="addressForm.provinceId"  @change="handleProvinceChange" show-search :filter-option="filterOption">
                  <a-select-option :value="province.id" v-for="province in provinceData" :key="province.id">
                    {{ province.name }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item label="" style="width: 100%;" prop="cityId">
                <a-select v-model="addressForm.cityId" @change="handleCityChange" show-search :filter-option="filterOption">
                  <a-select-option :value="city.id" v-for="city in cityData" :key="city.id">
                    {{ city.name }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
             <a-col :span="8">
              <a-form-model-item label="" style="width: 100%;" prop="areaId">
                <a-select v-model="addressForm.areaId" @change="handleDistrictChange" show-search :filter-option="filterOption">
                  <a-select-option :value="district.id" v-for="district in areaData" :key="district.id">
                    {{ district.name }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-form-model-item label="" style="width: 100%;" prop="shippingAddress">
           <a-textarea
              v-model="addressForm.shippingAddress"
              placeholder=""
              :auto-size="{ minRows: 3, maxRows: 5 }"
            />
          </a-form-model-item>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </a-card>
</template>
<script>
import { topicWinning, winningExport, topicWinningUpdate, province, city, district, contentCoupons} from '@/api/micromall/communityContent'
  const columns = [
    {
      title: '奖励名次',
      width: '100px',
      align: 'center',
      scopedSlots: { customRender: 'serialNumber' }
    },
    {
      title: '中奖用户',
      width: '200px',
      align: 'center',
      scopedSlots: { customRender: 'userInfo' }
    },
    {
      title: '中奖内容',
      width: '280px',
      align: 'left',
      scopedSlots: { customRender: 'content' }
    },
    {
      title: '获赞数',
      width: '280px',
      align: 'center',
      dataIndex: 'praiseNumber'
    },
    {
      title: '奖励类型',
      width: '120px',
      align: 'center',
      scopedSlots: { customRender: 'rewardType' }
    },
    {
      title: '奖品名称',
      width: '120px',
      align: 'center',
      dataIndex: 'rewardName'
    },
    {
      title: '奖品关联ID',
      width: '120px',
      align: 'center',
      dataIndex: 'rewardContact'
    },
    {
      title: '奖品图',
      width: '120px',
      align: 'center',
      scopedSlots: { customRender: 'img' }
    },
    {
      slots: { title: 'customAddress' },
      width: '220px',
      align: 'center',
      scopedSlots: { customRender: 'address' }
    },
    {
      title: '奖励发放状态',
      width: '200px',
      align: 'center',
      scopedSlots: { customRender: 'status' }
    },
    {
      title: '操作',
      width: '120px',
      align: 'center',
      fixed: 'right',
      scopedSlots: { customRender: 'action' }
    }
  ]
  export default {
    components: {
    },
    data() {
      return {
        item: {},
        rewardWhy: '',
        topicName: '',
        columns,
        winningList: [],
        expressForm: {
          express: ''
        },
        expressRules: {
          express: [
            { required: true, message: '请输入', trigger: 'blur' }
          ]
        },
        addressForm: {
          provinceId: '',
          province: '',
          cityId: '',
          city: '',
          areaId: '',
          area: '',
          shippingName: '',
          phone: '',
          shippingAddress: ''
        },
        addressRules: {
          provinceId: [
            { required: true, message: '请选择', trigger: 'change' }
          ],
          cityId: [
            { required: true, message: '请选择', trigger: 'change' }
          ],
          areaId: [
            { required: true, message: '请选择', trigger: 'change' }
          ],

          shippingName: [
            { required: true, message: '请输入', trigger: 'blur' }
          ],
          shippingAddress: [
            { required: true, message: '请输入', trigger: 'blur' }
          ],
          phone: [
            { required: true, message: '请输入', trigger: 'blur' },
            {
              validator: (rule, value, callback) => {
                const reg = /^(1)\d{10}$/
                if (!value && value !== 0) {
                  callback()
                } else {
                  if (reg.test(value)) {
                    callback()
                  } else {
                    return callback(new Error('请输入正确的格式'))
                  }
                }
              },
              trigger: 'blur'
            }
          ]
        },
        addressVisible: false,
        provinceData: [],
        cityData: [],
        areaData: [],
        expressVisible: false
      }
    },
    created() {
      this.getList()
    },
    computed: {},
    mounted() {
      //this.initAddress()
    },
    watch: {
    },
    methods: {
      // 获取列表
      getList() {
        const data = {
          id: this.$route.params.id
        }
        topicWinning(data).then(res => {
          if (res.code === 200) {
            this.winningList = res.data
            this.rewardWhy = this.winningList.length ? this.winningList[0].rewardWhy : ''
            this.topicName = this.winningList.length ? this.winningList[0].topicName : ''
          } else {
            this.$message.error(res.msg || res.message)
          }
        })
      },

      // 初始化省市区
      async initAddress(provinceId='', cityId='', areaId='') {
        await this.getProvince(provinceId)
        await this.getCity(cityId)
        await this.getDistrict(areaId)
      },

      // 省change
      async handleProvinceChange (v) {
        this.cityData = []
        this.areaData = []
        this.addressForm.provinceId = v
        this.addressForm.province = this.provinceData.filter(e => e.id == v)[0].name
        this.addressForm.cityId = ''
        this.addressForm.city = ''
        this.addressForm.areaId = ''
        this.addressForm.area = ''
        await this.getCity()
        this.handleCityChange(this.addressForm.cityId)
      },

      // 市change
      async handleCityChange (v) {
        this.areaData = []
        this.addressForm.cityId = v
        this.addressForm.city = this.cityData.filter(e => e.id == v)[0].name
        this.addressForm.areaId = ''
        this.addressForm.area = ''
        await this.getDistrict()
      },

      // 区change
      async handleDistrictChange (v) {
        this.addressForm.areaId = v
        this.addressForm.area = this.areaData.filter(e => e.id == v)[0].name
      },

      // 获取省
      getProvince(provinceId) {
        return new Promise(resolve => {
          province().then(res => {
             if (res.code === 200) {
              this.provinceData = res.data
              this.addressForm.provinceId = provinceId ? Number(provinceId) : this.provinceData[0].id
              this.addressForm.province = provinceId ? this.provinceData.filter(e => e.id == provinceId)[0].name : this.provinceData[0].name
              resolve()
            } else {
              this.$message.error(res.msg || res.message)
            }
          })
        })
      },

       // 获取市
      getCity (cityId) {
        if (!this.addressForm.provinceId) {
          return
        }
        const data = {
          provinceId: this.addressForm.provinceId
        }
        return new Promise(resolve => {
          city(data).then(res => {
            this.cityData = res.data
            this.addressForm.cityId = cityId ? Number(cityId) : this.cityData[0].id
            this.addressForm.city = cityId ? this.cityData.filter(e => e.id == cityId)[0].name : this.cityData[0].name
            resolve()
          })
        })
      },

       // 获取区
      getDistrict (areaId) {
        if (!this.addressForm.cityId) {
          return
        }
        const data = {
          cityId: this.addressForm.cityId
        }
        return new Promise(resolve => {
          district(data).then(res => {
            this.areaData = res.data
            this.addressForm.areaId = areaId ? Number(areaId) : this.areaData[0].id
            this.addressForm.area = areaId ? this.areaData.filter(e => e.id == areaId)[0].name : this.areaData[0].name
            resolve()
          })
        })
      },

      // 导出
      handleWinningExport() {
        if (!this.winningList.length) {
          this.$message.error('暂无数据！')
          return
        }
        window.location.href = winningExport + `?id=${this.$route.params.id}`
      },

      // 发放优惠券
      handleIssueCoupons(item) {
        const {contentId, rewardContact, id} = item
        const data = {
          contentId,
          rewardContact,
          id
        }
        contentCoupons(data).then(res => {
          if (res.code === 200) {
            this.getList()
          } else {
            this.$message.error(res.msg || res.message)
          }
        })
      },

      // 显示物流输入框
      handleShowExpressModal(item) {
        this.expressVisible = true
        this.item = item
      },

      // 发放物品
      handleIssueGoods() {
        this.$refs.expressRulesForm.validate(valid => {
          if (valid) {
            this.expressVisible = false
             const data = {
              ...this.item,
              status: 0,
              orderNo: this.expressForm.express
            }
            this.getTopicWinningUpdate(data)
          } else {
            console.log('error submit!!');
            return false;
          }
        })
      },

      // 修改奖品信息
      getTopicWinningUpdate(data) {
        topicWinningUpdate(data).then(res => {
          if (res.code === 200) {
            this.getList()
            this.expressForm.express = ''
            this.addressForm = {
              provinceId: '',
              province: '',
              cityId: '',
              city: '',
              areaId: '',
              area: '',
              shippingName: '',
              phone: '',
              shippingAddress: ''
            }
          } else {
            this.$message.error(res.msg || res.message)
          }
        })
      },

       // 详情
      handleDetails(id) {
        this.$router.push(`/micromall/community/contentManagement/details/${id}`)
      },

      // 修改地址
     handleShowAddressModal(item) {
        this.addressVisible = true
        this.item = item
        const { provinceId, cityId, areaId, shippingName, phone, shippingAddress } = this.item
        this.addressForm = {
          shippingName: shippingName ? shippingName : '',
          phone: phone ? phone : '',
          shippingAddress: shippingAddress ? shippingAddress : ''
        }
        this.initAddress(provinceId, cityId, areaId)
     },

      // 确认修改地址
      handleSubmit() {
        this.$refs.addressRulesForm.validate(valid => {
          if (valid) {
            this.addressVisible = false
            const data = {
              ...this.item,
              ...this.addressForm
            }
            this.getTopicWinningUpdate(data)
          } else {
            console.log('error submit!!');
            return false;
          }
        })
      },
      filterOption(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        )
      },
    }
  }
</script>
<style lang="less" scoped>
.title{
  font-weight: bold;
}
  /deep/ .ant-tabs-bar {
    margin-bottom: 0;
  }

  .img-wrapper {
    display: flex;

    .img-list {
      display: flex;
    }

    .img-text {
      line-height: 60px;
      color: #999;
    }
  }

  .img {
    display: block;
    margin: 0 auto;
    width: 65px;
    height: 65px;
    border: 1px dashed #f5f5f5;
    object-fit: scale-down;
  }

  .content {
    margin-top: 0 !important;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    word-break: break-all; /* 追加这一行代码 */
    /* autoprefixer: off */
    -webkit-box-orient: vertical;
    /* autoprefixer: on */
  }
  .content-btn{
      display: flex;
      justify-content: space-between;
      color: rgb(87, 87, 255);
      margin-right: 40px;
      cursor: pointer;
    }
  .product {
    display: flex;
    overflow: hidden;
    .img{
      margin: 0;
    }
    .product-name{
      flex: 1;
      margin-left: 5px;
      width: 80px;
      text-align: left;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 3;
      word-break: break-all; /* 追加这一行代码 */
      /* autoprefixer: off */
      -webkit-box-orient: vertical;
      /* autoprefixer: on */
    }
  }
  .product-list {
    .product-item {
      line-height: 18px;
      text-align: left;
    }

    .product-num {
      cursor: pointer;
      text-align: left;
    }
  }
  .content-record{
    position: absolute;
    right: 0;
    top: 15px;
  }
  .image-video-wrapper{
    position: relative;
    width: 60px;
    height: 60px;
    margin: 0 auto;
    .img-num{
      position: absolute;
      left: 0;
      bottom: 0;
      width: 100%;
      line-height: 18px;
      text-align: center;
      font-size: 12px;
      color:#fff;
      background: rgba(0, 0, 0, 0.5);
    }
  }
</style>
